<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户中心 - CPPSearch</title>
    <link rel="stylesheet" href="css/styles.css">
    <style>
        .user-center-container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
        }
        .user-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 10px;
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .user-info {
            display: flex;
            align-items: center;
            gap: 20px;
        }
        .user-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 32px;
            color: #667eea;
            font-weight: bold;
        }
        .user-details h2 {
            margin: 0 0 10px 0;
            font-size: 24px;
        }
        .user-details p {
            margin: 5px 0;
            opacity: 0.9;
        }
        .user-actions {
            display: flex;
            gap: 10px;
        }
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            text-decoration: none;
            color: white;
            transition: all 0.3s;
        }
        .btn-logout {
            background: rgba(255,255,255,0.2);
            border: 2px solid white;
        }
        .btn-logout:hover {
            background: white;
            color: #667eea;
        }
        .dashboard {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        .card {
            background: white;
            border-radius: 10px;
            padding: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            transition: transform 0.3s;
        }
        .card:hover {
            transform: translateY(-5px);
        }
        .card h3 {
            margin: 0 0 20px 0;
            color: #333;
            font-size: 18px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .card-icon {
            width: 24px;
            height: 24px;
            background: #007bff;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 14px;
        }
        .balance-amount {
            font-size: 32px;
            font-weight: bold;
            color: #28a745;
            margin: 10px 0;
        }
        .btn-recharge {
            background: #28a745;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .btn-recharge:hover {
            background: #218838;
        }
        .keyword-list {
            max-height: 200px;
            overflow-y: auto;
        }
        .keyword-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            border-bottom: 1px solid #eee;
        }
        .keyword-item:last-child {
            border-bottom: none;
        }
        .keyword-weight {
            background: #007bff;
            color: white;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
        }
        .add-keyword-form {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }
        .add-keyword-form input {
            flex: 1;
            padding: 8px;
            border: 2px solid #ddd;
            border-radius: 5px;
        }
        .add-keyword-form button {
            padding: 8px 15px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        .history-list {
            max-height: 200px;
            overflow-y: auto;
        }
        .history-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
        }
        .history-item:last-child {
            border-bottom: none;
        }
        .history-date {
            color: #6c757d;
            font-size: 14px;
        }
        .history-amount {
            font-weight: bold;
            color: #28a745;
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        .modal-content {
            background-color: white;
            margin: 15% auto;
            padding: 30px;
            border-radius: 10px;
            width: 400px;
            max-width: 90%;
        }
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }
        .close:hover {
            color: black;
        }
        .recharge-options {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
            margin: 20px 0;
        }
        .recharge-option {
            padding: 15px;
            border: 2px solid #ddd;
            border-radius: 5px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        .recharge-option:hover {
            border-color: #007bff;
            background: #f8f9fa;
        }
        .recharge-option.selected {
            border-color: #007bff;
            background: #e3f2fd;
        }
        .recharge-amount {
            font-size: 18px;
            font-weight: bold;
            color: #28a745;
        }
        .recharge-bonus {
            font-size: 14px;
            color: #dc3545;
            margin-top: 5px;
        }
        .message {
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
            display: none;
        }
        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
    </style>
</head>
<body>
    <header>
        <div class="container">
            <h1>CPPSearch</h1>
            <nav>
                <ul>
                    <li><a href="index.html">首页</a></li>
                    <li><a href="user_center.html" class="active">用户中心</a></li>
                    <li><a href="#" onclick="logout()">退出登录</a></li>
                </ul>
            </nav>
        </div>
    </header>

    <main>
        <div class="container">
            <div class="user-center-container">
                <!-- 用户头部信息 -->
                <div class="user-header">
                    <div class="user-info">
                        <div class="user-avatar" id="userAvatar">U</div>
                        <div class="user-details">
                            <h2 id="username">用户名</h2>
                            <p id="userEmail">user@example.com</p>
                            <p id="joinDate">加入时间：2024-01-01</p>
                        </div>
                    </div>
                    <div class="user-actions">
                        <button class="btn btn-logout" onclick="logout()">退出登录</button>
                    </div>
                </div>

                <!-- 仪表板 -->
                <div class="dashboard">
                    <!-- 账户余额 -->
                    <div class="card">
                        <h3>
                            <div class="card-icon">¥</div>
                            账户余额
                        </h3>
                        <div class="balance-amount" id="balance">¥0.00</div>
                        <p style="color: #6c757d; margin: 10px 0;">可用于搜索和AI服务</p>
                        <button class="btn-recharge" onclick="showRechargeModal()">立即充值</button>
                    </div>

                    <!-- 关键词权重 -->
                    <div class="card">
                        <h3>
                            <div class="card-icon">K</div>
                            关键词权重
                        </h3>
                        <div class="keyword-list" id="keywordList">
                            <p style="color: #6c757d; text-align: center; padding: 20px;">暂无关键词</p>
                        </div>
                        <div class="add-keyword-form">
                            <input type="text" id="newKeyword" placeholder="输入关键词">
                            <input type="number" id="newWeight" placeholder="权重" min="1" max="10" value="5">
                            <button onclick="addKeyword()">添加</button>
                        </div>
                    </div>

                    <!-- 支付历史 -->
                    <div class="card">
                        <h3>
                            <div class="card-icon">H</div>
                            支付历史
                        </h3>
                        <div class="history-list" id="historyList">
                            <p style="color: #6c757d; text-align: center; padding: 20px;">暂无支付记录</p>
                        </div>
                    </div>
                </div>

                <!-- 消息提示 -->
                <div class="message" id="message"></div>
            </div>
        </div>
    </main>

    <!-- 充值模态框 -->
    <div id="rechargeModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeRechargeModal()">&times;</span>
            <h2>账户充值</h2>
            <p style="color: #6c757d; margin: 10px 0;">选择充值金额，享受更多搜索和AI服务</p>
            
            <div class="recharge-options">
                <div class="recharge-option" onclick="selectRecharge(this, 10)">
                    <div class="recharge-amount">¥10</div>
                    <div class="recharge-bonus">基础套餐</div>
                </div>
                <div class="recharge-option" onclick="selectRecharge(this, 50)">
                    <div class="recharge-amount">¥50</div>
                    <div class="recharge-bonus">赠送¥5</div>
                </div>
                <div class="recharge-option" onclick="selectRecharge(this, 100)">
                    <div class="recharge-amount">¥100</div>
                    <div class="recharge-bonus">赠送¥15</div>
                </div>
                <div class="recharge-option" onclick="selectRecharge(this, 200)">
                    <div class="recharge-amount">¥200</div>
                    <div class="recharge-bonus">赠送¥40</div>
                </div>
            </div>
            
            <button class="btn-recharge" style="width: 100%; padding: 15px; font-size: 16px;" onclick="processRecharge()">
                确认充值
            </button>
        </div>
    </div>

    <footer>
        <div class="container">
            <p>&copy; 2025 CPPSearch. 保留所有权利。</p>
        </div>
    </footer>

    <script>
        let currentUser = null;
        let selectedRechargeAmount = 0;

        // 页面加载时初始化
        window.addEventListener('load', function() {
            checkLoginStatus();
            loadUserInfo();
            loadBalance();
            loadKeywords();
            loadPaymentHistory();
        });

        // 检查登录状态
        function checkLoginStatus() {
            const user = localStorage.getItem('currentUser');
            if (!user) {
                window.location.href = 'login.html';
                return;
            }
            currentUser = JSON.parse(user);
        }

        // 加载用户信息
        async function loadUserInfo() {
            if (!currentUser) return;
            
            try {
                const response = await fetch('/api/user/info', {
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.getItem('sessionId')
                    }
                });
                
                if (response.ok) {
                    const result = await response.json();
                    if (result.success) {
                        updateUserInfo(result.user);
                    }
                }
            } catch (error) {
                console.error('Failed to load user info:', error);
            }
        }

        // 更新用户信息显示
        function updateUserInfo(user) {
            document.getElementById('username').textContent = user.username;
            document.getElementById('userEmail').textContent = user.email;
            document.getElementById('joinDate').textContent = '加入时间：' + (user.created_at || '2024-01-01');
            
            // 更新头像显示用户名首字母
            const avatar = document.getElementById('userAvatar');
            avatar.textContent = user.username.charAt(0).toUpperCase();
        }

        // 加载余额
        async function loadBalance() {
            if (!currentUser) return;
            
            try {
                const response = await fetch('/api/user/balance', {
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.getItem('sessionId')
                    }
                });
                
                if (response.ok) {
                    const result = await response.json();
                    if (result.success) {
                        document.getElementById('balance').textContent = '¥' + result.balance.toFixed(2);
                    }
                }
            } catch (error) {
                console.error('Failed to load balance:', error);
            }
        }

        // 加载关键词
        async function loadKeywords() {
            if (!currentUser) return;
            
            try {
                const response = await fetch('/api/keywords/list', {
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.getItem('sessionId')
                    }
                });
                
                if (response.ok) {
                    const result = await response.json();
                    if (result.success) {
                        updateKeywordList(result.keywords);
                    }
                }
            } catch (error) {
                console.error('Failed to load keywords:', error);
            }
        }

        // 更新关键词列表
        function updateKeywordList(keywords) {
            const keywordList = document.getElementById('keywordList');
            
            if (!keywords || keywords.length === 0) {
                keywordList.innerHTML = '<p style="color: #6c757d; text-align: center; padding: 20px;">暂无关键词</p>';
                return;
            }
            
            keywordList.innerHTML = keywords.map(keyword => `
                <div class="keyword-item">
                    <span>${keyword.keyword}</span>
                    <span class="keyword-weight">${keyword.weight}</span>
                </div>
            `).join('');
        }

        // 添加关键词
        async function addKeyword() {
            const keyword = document.getElementById('newKeyword').value.trim();
            const weight = parseInt(document.getElementById('newWeight').value);
            
            if (!keyword) {
                showMessage('请输入关键词', 'error');
                return;
            }
            
            if (weight < 1 || weight > 10) {
                showMessage('权重必须在1-10之间', 'error');
                return;
            }
            
            try {
                const response = await fetch('/api/keywords/set', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + localStorage.getItem('sessionId')
                    },
                    body: JSON.stringify({
                        keyword: keyword,
                        weight: weight
                    })
                });
                
                const result = await response.json();
                if (result.success) {
                    showMessage('关键词添加成功', 'success');
                    document.getElementById('newKeyword').value = '';
                    document.getElementById('newWeight').value = '5';
                    loadKeywords();
                } else {
                    showMessage(result.message || '添加失败', 'error');
                }
            } catch (error) {
                showMessage('网络错误，请稍后重试', 'error');
                console.error('Failed to add keyword:', error);
            }
        }

        // 加载支付历史
        async function loadPaymentHistory() {
            if (!currentUser) return;
            
            try {
                const response = await fetch('/api/payment/history', {
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.getItem('sessionId')
                    }
                });
                
                if (response.ok) {
                    const result = await response.json();
                    if (result.success) {
                        updatePaymentHistory(result.payments);
                    }
                }
            } catch (error) {
                console.error('Failed to load payment history:', error);
            }
        }

        // 更新支付历史
        function updatePaymentHistory(payments) {
            const historyList = document.getElementById('historyList');
            
            if (!payments || payments.length === 0) {
                historyList.innerHTML = '<p style="color: #6c757d; text-align: center; padding: 20px;">暂无支付记录</p>';
                return;
            }
            
            historyList.innerHTML = payments.map(payment => `
                <div class="history-item">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <div>${payment.product_name}</div>
                            <div class="history-date">${payment.create_time}</div>
                        </div>
                        <div class="history-amount">+¥${payment.amount.toFixed(2)}</div>
                    </div>
                </div>
            `).join('');
        }

        // 显示充值模态框
        function showRechargeModal() {
            document.getElementById('rechargeModal').style.display = 'block';
        }

        // 关闭充值模态框
        function closeRechargeModal() {
            document.getElementById('rechargeModal').style.display = 'none';
            selectedRechargeAmount = 0;
            document.querySelectorAll('.recharge-option').forEach(option => {
                option.classList.remove('selected');
            });
        }

        // 选择充值金额
        function selectRecharge(element, amount) {
            document.querySelectorAll('.recharge-option').forEach(option => {
                option.classList.remove('selected');
            });
            element.classList.add('selected');
            selectedRechargeAmount = amount;
        }

        // 处理充值
        async function processRecharge() {
            if (selectedRechargeAmount === 0) {
                showMessage('请选择充值金额', 'error');
                return;
            }
            
            try {
                const response = await fetch('/api/payment/create', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + localStorage.getItem('sessionId')
                    },
                    body: JSON.stringify({
                        product_name: `充值¥${selectedRechargeAmount}`,
                        amount: selectedRechargeAmount,
                        order_type: 'recharge'
                    })
                });
                
                const result = await response.json();
                if (result.success) {
                    // 跳转到支付页面
                    window.open(result.payment_url, '_blank');
                    closeRechargeModal();
                    showMessage('支付链接已生成，请完成支付', 'success');
                    
                    // 定期检查支付状态
                    setTimeout(() => {
                        loadBalance();
                        loadPaymentHistory();
                    }, 5000);
                } else {
                    showMessage(result.message || '创建支付订单失败', 'error');
                }
            } catch (error) {
                showMessage('网络错误，请稍后重试', 'error');
                console.error('Failed to process recharge:', error);
            }
        }

        // 显示消息
        function showMessage(text, type) {
            const message = document.getElementById('message');
            message.textContent = text;
            message.className = 'message ' + type;
            message.style.display = 'block';
            
            setTimeout(() => {
                message.style.display = 'none';
            }, 3000);
        }

        // 退出登录
        function logout() {
            localStorage.removeItem('currentUser');
            localStorage.removeItem('sessionId');
            window.location.href = 'login.html';
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modal = document.getElementById('rechargeModal');
            if (event.target === modal) {
                closeRechargeModal();
            }
        }
    </script>
</body>
</html>